package utils

import (
	"errors"
	"github.com/golang-jwt/jwt/v4"
	"mxshop-api/user-web/global"
	"time"
)

var (
	TokenExpired     = errors.New("Token is expired")
	TokenNotValidYet = errors.New("Token not active yet")
	TokenMalformed   = errors.New("That's not even a token")
	TokenInvalid     = errors.New("Couldn't handle this token:")
)

type CustomClaims struct {
	ID          int32
	NickName    string
	AuthorityId int32
	jwt.StandardClaims
}

type JWT struct {
	SigningKey []byte
}

func NewJWT() *JWT {
	return &JWT{
		[]byte(global.ServerConfig.Jwt.Key),
	}
}

// CreateToken 生成token
func (j *JWT) CreateToken(id, roleId int32, nickName string) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, &CustomClaims{
		ID:          id,
		NickName:    nickName,
		AuthorityId: roleId,
		StandardClaims: jwt.StandardClaims{
			Issuer:    "lshsh",
			ExpiresAt: time.Now().Add(time.Hour * 24 * 2).Unix(), // 3天过期
		},
	})
	return token.SignedString(j.SigningKey)
}

// ParseToekn 解析token
func (j *JWT) ParseToekn(tokenString string) (*CustomClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		return j.SigningKey, nil
	})
	if err != nil {
		if ve, ok := err.(*jwt.ValidationError); ok {
			if ve.Errors&jwt.ValidationErrorMalformed != 0 {
				return nil, TokenMalformed
			} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
				// Token is expired
				return nil, TokenExpired
			} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
				return nil, TokenNotValidYet
			} else {
				return nil, TokenInvalid
			}
		}
	}
	if token != nil {
		if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
			return claims, nil
		}
		return nil, TokenInvalid

	} else {
		return nil, TokenInvalid

	}
}
